<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title data-i18n="title">Stripe 支付示例</title>
    <script src="https://js.stripe.com/v3/"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f6f8;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
        }
        .payment-box {
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            width: 360px;
        }
        h2 {
            text-align: center;
            margin-bottom: 20px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        input[type="text"], input[type="number"] {
            width: 94%;
            padding: 10px;
            margin-bottom: 15px;
            border: 1px solid #ccc;
            border-radius: 5px;
        }
        select {
            width: 100%;
            padding: 10px;
            margin-bottom: 15px;
            border: 1px solid #ccc;
            border-radius: 5px;
        }
        #card-element {
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        button {
            width: 100%;
            padding: 12px;
            background-color: #6772e5;
            color: white;
            border: none;
            border-radius: 5px;
            font-size: 16px;
            cursor: pointer;
        }
        #error-message {
            color: red;
            margin-top: 10px;
            text-align: center;
        }
    </style>
</head>
<body>
<div class="payment-box">
    <h2 data-i18n="pay_title">信用卡支付</h2>
    <label for="username" data-i18n="label_username">用户名</label>
    <input type="text" id="username" name="username" value="liqiye" required>
    <label for="orderId" data-i18n="label_orderId">订单 ID（我们业务系统的表id，用来关联入库）</label>
    <input type="text" id="orderId" name="orderId"  required>
    <form id="payment-form">
        <label for="amount" data-i18n="label_amount">金额</label>
        <input type="number" id="amount" name="amount" placeholder="10.00" required step="0.01" min="0.5">

        <label for="currency" data-i18n="label_currency">货币</label>
        <select id="currency">
            <option value="eur">EUR - 欧元</option>
            <option value="usd">USD - 美元</option>
        </select>

        <div id="exchange-info" style="font-size: 14px; margin-bottom: 10px;"></div>

        <label for="card-element" data-i18n="label_card">卡信息</label>
        <div id="card-element"></div>

        <button type="submit" data-i18n="btn_pay">立即支付</button>
        <div id="error-message"></div>
    </form>
</div>

<script>
    const stripe = Stripe("${stripePublicKey}");
    const elements = stripe.elements();
    const card = elements.create("card");
    card.mount("#card-element");

    const exchangeRates = {};

    async function preloadRates() {
        const currencies = ["usd", "eur"];
        for (const currency of currencies) {
            try {
                const url = "/currency/convert?from=" + currency.toUpperCase() + "&to=CNY&amount=1";
                const res = await fetch(url);
                const data = await res.json();
                if (data.convertedAmount) {
                    exchangeRates[currency.toLowerCase()] = data.convertedAmount; // 单位：1币种 = X人民币
                }
            } catch (e) {
                console.warn("获取汇率失败", currency, e);
            }
        }
    }


    const updateExchange = () => {
        const raw = document.getElementById("amount").value;
        const amount = parseFloat(raw);
        const currency = document.getElementById("currency").value;

        if (!amount || isNaN(amount) || amount < 0.01) {
            document.getElementById("exchange-info").textContent = '';
            return;
        }

        if (currency === 'usd') {
            const usdAmount = (amount * exchangeRates.usd).toFixed(2);
            document.getElementById("exchange-info").textContent = `≈ ¥` + usdAmount;
        } else if (currency === 'eur') {
            const eurAmount = (amount * exchangeRates.eur).toFixed(2);
            document.getElementById("exchange-info").textContent = `≈ ¥` + eurAmount;
        }
    };

    document.getElementById("amount").addEventListener("input", updateExchange);
    document.getElementById("currency").addEventListener("change", updateExchange);

    window.addEventListener("load", preloadRates);


    document.getElementById("payment-form").addEventListener("submit", async (event) => {
        event.preventDefault();

        const amount = document.getElementById("amount").value;
        const currency = document.getElementById("currency").value;
        const orderId = document.getElementById("orderId").value;

        if (!amount || isNaN(amount) || parseFloat(amount) < 0.5) {
            document.getElementById("error-message").textContent = "请输入合法的金额，最小 $0.50";
            return;
        }

        const res = await fetch("/stripe/intent/create", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({
                amount: amount,
                currency: currency,
                paymentMethod: "card",
                orderId: orderId
            })
        });

        const username = document.getElementById("username").value;

        const result = await res.json();
        if (!result.clientSecret) {
            document.getElementById("error-message").textContent = "创建支付失败。";
            return;
        }

        // 调用 Stripe 的 API ，完成真正的扣款
        const { error, paymentIntent } = await stripe.confirmCardPayment(result.clientSecret, {
            payment_method: {
                card: card,
                billing_details: {
                    // 这个参数也是会入库 stripe 的，页面展示
                    name: username
                }
            }
        });

        if (error) {
            document.getElementById("error-message").textContent = error.message;
        } else {
            console.info("paymentIntentId=" + paymentIntent.id)
            const recordRes = await fetch("/stripe/charge/record?paymentIntentId=" + encodeURIComponent(paymentIntent.id), {
                method: "POST"
            });
            if (!recordRes.ok) {
                console.error("记录付款信息失败");
            }
            alert("支付成功！");
        }
    });

    const i18n = {
        zh: {
            title: "Stripe 支付示例",
            pay_title: "信用卡支付",
            label_amount: "金额",
            label_currency: "货币",
            label_card: "卡信息",
            btn_pay: "立即支付"
        },
        en: {
            title: "Stripe Payment Demo",
            pay_title: "Credit Card Payment",
            label_amount: "Amount",
            label_currency: "Currency",
            label_card: "Card Info",
            btn_pay: "Pay Now"
        }
    };

    const lang = navigator.language.startsWith("zh") ? "zh" : "en";
    document.querySelectorAll("[data-i18n]").forEach(el => {
        const key = el.getAttribute("data-i18n");
        if (i18n[lang][key]) el.textContent = i18n[lang][key];
    });
</script>
</body>
</html>
